package com.climber.spb_rabbitmq.autoack;

import com.climber.spb_rabbitmq.utils.RabbitMQUtils;
import com.rabbitmq.client.CancelCallback;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DeliverCallback;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

public class AConsumer2 {
    private static final String TASK_QUEUE_NAME="ack_queue";

    public static void main(String[] args) {
        try {
            Channel channel = RabbitMQUtils.getChannel();
            channel.basicQos(2);
            System.out.println("MConsumer2*********");
            DeliverCallback deliverCallback=(consumerTag,message)->{
                String s = new String(message.getBody(), StandardCharsets.UTF_8);
                System.out.println("consumer2 received message : "+s);
                try {
//                    该消费者处理慢，接受消息后人为终止后，消息会回到队列给其他消费者
                    Thread.sleep(1000*8);
//                    两个消费者轮流执行
//                    Thread.sleep(1000*2);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("consumer2 finished");
//                注意在自动应答的机制下，依旧采用手动应答，就会报错提示连接已经关闭，
//                因为在自动应答模式下，消息发给消费者后就会直接删除
//                channel.basicAck(message.getEnvelope().getDeliveryTag(),false);
            };
            CancelCallback cancelCallback=(consumerTag)->{
                System.out.println(consumerTag);
                System.out.println("receive interrupted");
            };
            channel.basicConsume(TASK_QUEUE_NAME,true,deliverCallback,cancelCallback);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
}
